<?php
include('common/constants.php');
include('common/db.php');

if (!isset( $_GET )){
	echo "Nothing to save.";
}

//create array to temporarily grab variables
$input_arr = array();
//grabs the $_GET variables and adds slashes
foreach ($_GET as $key => $input_arr) {
	$_GET[$key] = addslashes(htmlspecialchars($input_arr));
}

$advert_id = $_GET['advert_id'];
$seat_count = $_GET['seat_count'];
$res_id = $_GET['res_id'];


//Getting already booked seats
$slctSql = " SELECT * FROM seat WHERE advert_id='{$advert_id}' AND seat_status = 'booked' AND reservation_id = '{$res_id}'";
$result = mysql_query($slctSql) or trigger_error(mysql_error());
$bookedSeats = mysql_num_rows($result);

//Getting available seats
$slctSql2 = " SELECT * FROM seat WHERE advert_id='{$advert_id}' AND seat_status = 'open'";
$result2 = mysql_query($slctSql2) or trigger_error(mysql_error());
$availableSeats = mysql_num_rows($result2);

//Getting the balance seats of seat requirement of requesting user
$requiredSeats = $seat_count - $bookedSeats;


if ($requiredSeats > $availableSeats) {
	//echo "Not enough seats are available.";
	echo "fail";

} else if ($bookedSeats <= $seat_count) {
	
	if ($bookedSeats < $seat_count) {
		
		$sql = " UPDATE `seat` SET seat_status = 'booked', `reservation_id`='{$res_id}' WHERE advert_id='{$advert_id}' AND seat_status = 'open' LIMIT " . $requiredSeats;
		if(mysql_query($sql)){
			$message = "";
			$message .= "Hi, <br />";
			$message .= "Your reservation has been confirmed. <br />";
			$message .= "Please log in to http://carpooling.lk for more information. <br />";
		
			$to = $_GET['email'];
			$subject = "CarPooling.lk - Reservation  confirmation";
			$headers = "From: " . CONTACT_MAIL_FROM . "\r\n";
			$headers .= 'Cc: ' . CONTACT_MAIL_INTERNAL_CC . "\r\n";
			$headers .= 'Bcc: ' . CONTACT_MAIL_INTERNAL_BCC . "\r\n";
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
				
			if (mail($to, $subject, $message, $headers)) {
				//echo 'Your message has been sent.';
			} else {
				//echo 'There was a problem sending the email.';
			}
			
			//Check if all the seats requested by the reservation are fully accepted.
			$sqlChkResStatus = " SELECT r.seat_count  FROM `reservation` r, seat s WHERE r.reservation_id='{$res_id}'  AND r.reservation_id=s.reservation_id AND s.seat_status='booked' "; 
			$chkStatusResult = mysql_query($sqlChkResStatus) or trigger_error(mysql_error());
			$seatsBookedAlready = mysql_num_rows($chkStatusResult);
			if (mysql_result($chkStatusResult,0,"r.seat_count") == $seatsBookedAlready) {
				$updateSql = " UPDATE `reservation` SET reservation_status = 'accepted' WHERE reservation_id='{$res_id}'";
				$updateResult = mysql_query($updateSql) or trigger_error(mysql_error());
			}
			
			echo "success";

		}else{
			echo "fail";
		}
	}


} else {
	//echo "Seats full.";
	echo "fail";
}
?>